import { EditorGamePanel } from './../EditorGamePanel/EditorGamePanel';
import { _decorator, Component, Node, Button, Label } from 'cc';
import { BaseView } from '../../../../scripts/libs/rxjs/cc3/BaseView';
import { BindButton } from '../../../../scripts/libs/rxjs/cc3/BindButton';
import { ReactiveProperty } from '../../../../scripts/libs/rxjs/cc3/ReactiveProperty';
import { lm } from '../../LobbyManager';
import { ResourceHelper } from '../../ResourceHelper';
import { FlowStatus } from '../../Enums';
import { gm } from '../../../../scripts/managers/GameManager';
import { udm } from '../../../../scripts/managers/UserDataManager';
import { BuyHeartPanel } from '../BuyHeartPanel/BuyHeartPanel';
const { ccclass, property } = _decorator;

@ccclass('StageXButton')
export class StageXButton extends BaseView {

    stageId = ReactiveProperty.Create(0);

    @property(Button)
    selfButton: Button = null;

    @property(Label)
    stageIdLabel: Label = null;

    useObserves() {
        return [
            BindButton(this.selfButton).subscribe(this.selfButtonClicked.bind(this)),
            // this.stageId.subscribe(_ => this.stageIdLabel.string = `Stage ${_}`),
            this.stageId.subscribe(_ => this.stageIdLabel.string = `LEVEL ${_}`),
        ];
    }

    selfButtonClicked() {
        lm.customLoadingReasons.add('load_stage');
        ResourceHelper.LoadStageAssets(this.stageId.value).subscribe(stageInfo => {
            if (stageInfo != null) {
                lm.customLoadingReasons.delete('load_stage');
                if (stageInfo.stageId != null && stageInfo.stageId != this.stageId.value) {
                    this.warn('StageId in json is not match with stageId in file name.');
                    return;
                }
                stageInfo.stageId = this.stageId.value;
                gm.stageInfo.value = stageInfo;
                if (gm.editEnabled.value) {
                    lm.flowStatus.value = FlowStatus.EditorGame;
                } else {
                    let curHeartCount = udm.getHeartCount();
                    if (udm.getRemainMsToOverInfHeart() > 0 || curHeartCount > 0) {
                        lm.flowStatus.value = FlowStatus.Game;
                    } else {
                        BuyHeartPanel.StartProcess().subscribe(_ => {
                            if (_ == 'continue') {
                                lm.flowStatus.value = FlowStatus.Game;
                            }
                        });
                    }
                }
            } else {
                lm.customLoadingReasons.delete('load_stage');
            }
        });
    }

}


